package com.zcsy.manage.service.system.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.commons.util.Globals;
import com.zcsy.manage.model.base.OwnerHouse;
import com.zcsy.manage.model.system.RoleUser;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.model.system.bo.RegisterInfo;
import com.zcsy.manage.persistence.base.CellHouseDao;
import com.zcsy.manage.persistence.base.OwnerHouseDao;
import com.zcsy.manage.persistence.system.UserDao;
import com.zcsy.manage.service.system.IUserService;

/**
 * @Title: UserServiceImpl.java
 * @Package： com.zcsy.shop.service.impl 
 * @Description: 用户相关服务层接口实现类
 *
 * @author tanghan barbadosliy@163.com
 * @Copyright: 2015 武汉中财数元信息技术有限公司 All rights reserved.
 * @date 2015年7月7日
 * @version 1.0
 * @see JDK1.7.0_75
 * @since
 */
@Service
public class UserServiceImpl extends SystemComService implements IUserService {

	/**
	 * 用户账号最少六位
	 */
	public static final int MIN_USER_NO_NUM = 6;
	
	@Autowired
	private UserDao userDao;
	
	@Autowired
    private CellHouseDao cellHouseDao;
	
	@Autowired
    private OwnerHouseDao ownerHouseDao;
	
	@Override
	public User selectByPrimaryKey(String id) {
		return userDao.selectByPrimaryKey(id);
	}

	@Override
	public User selectByLoginName(String loginname) {
		User user = userDao.selectByLoginName(loginname);
		return user;
	}
	
	@Override
	public boolean selectUserIfExists(String loginname) {
		return userDao.selectByLoginName(loginname) != null;
	}
	
	@Override
	public List<User> selectUserIfPhoneExists(String phone , int type) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("phone", phone);
		map.put("type", type);
		return userDao.selectUserIfPhoneExists(map);
	}

	@Override
	public int deleteByPrimaryKey(String id) {
		return userDao.deleteByPrimaryKey(id);
	}

	@Override
	public int insert(User record) {
		return userDao.insert(record);
	}

	@Override
	public int updateByPrimaryKeySelective(User record) {
		return userDao.updateByPrimaryKeySelective(record);
	}

	@Override
	public List<User> getAll() {
		return userDao.getAll();
	}

    /* 
     * (non-Javadoc)
     * @see com.framework.service.IUserService#queryUser(com.framework.model.User)
     */
    @Override
    public List<User> queryUser(User record){
        return userDao.queryUser(record);
    }

    @Override
    public int updateState(String id, int state) {
        Map<String, Object> map=new HashMap<String, Object>();
        map.put("id", id);
        map.put("state", state);
        return userDao.updateState(map);
    }
    
    @Override
    public int savePassword(User userVo) {
        // 修改密码操作
    	String id = userVo.getId();
        String password = userVo.getPwd();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", id);
        map.put("pwd", password);
        return userDao.savePassword(map);

    }

	@Override
	public List<User> selectByRoleId(String roleId) {
		return userDao.selectByRoleId(roleId);
	}

    @Override
    public User Identify(String identification) {
        User user = null;
        try {
            user = userDao.Identify(identification);
        } catch(Exception e) {
            e.printStackTrace();
        }
        return user;
    }

	@Override
	public List<User> selectByOrgId(String orgId) {
		return userDao.selectByOrgId(orgId);
	}

    @Override
    public void updateRoleUser(String userId, String[] roles) {
        userDao.deleteRoleUser(userId);
        if(roles != null && roles.length > 0) {
            for(String roleId : roles){
               RoleUser roleUser = new RoleUser();
               roleUser.setRoleId(roleId);
               roleUser.setUserId(userId);
               roleUser.setId(UniqueNumberUtils.get18UniqueNumber());
               userDao.insertRoleUser(roleUser);
            }
        }
        
    }

    @Override
    public List<RoleUser> queryRoleByUserId(String userId) {
    	if(StringUtils.isEmpty(userId) || userId.equals(Constants.ID_ZERO)){
    		return new ArrayList<RoleUser>();
    	}
    	
        return userDao.queryRoleByUserId(userId);
    }

	@Override
	public List<RoleUser> queryRoleByUserIdAndUserType(String userId,
			int userType) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userId", userId);
		map.put("roleType", userType);
		return userDao.queryRoleByUserIdAndUserType(map);
	}

	@Override
	public void clearOwnerIntegral() {
		userDao.clearOwnerIntegral();
	}

	@Override
	public User userLogin(User user) {
		// TODO Auto-generated method stub

		return userDao.userLogin(user);
	}
	/* (non-Javadoc)
	 * 获取当前用户类型的最大帐户编号
	 */
	@Override
	public String getNewUserNo(int userType) {
        String operation = Globals.getConfig("account_operation");//运营
        String shopper = Globals.getConfig("account_shopper");    //商户
        String dispatch = Globals.getConfig("account_dispatch");  //配送
        String property = Globals.getConfig("account_property");  //物业
        String owner = Globals.getConfig("account_owner");        //业主

        //存放生成的帐户编号
        StringBuffer account = new StringBuffer();
       
        //获取当前用户类型最大编号
        String newUserNo = userDao.getNewUserNo(userType);
        if(newUserNo == null){
            newUserNo = "000000";
         }else {
        	newUserNo = newUserNo.substring(1);
		}
        switch (userType) {
        case Constants.ADMIN_TYPE:
        case Constants.OPERATION_TYPE:
        	account.append(operation);
        	break;
        case Constants.PROPERTY_TYPE:
        	account.append(property);
        	break;
        case Constants.BUSINESS_TYPE:
        	account.append(shopper);
        	break;
        case Constants.DISTRIBUTION_TYPE:
        	account.append(dispatch);
        	break;
        case Constants.OWNER_TYPE:
        	account.append(owner);
        	break;
        default:
        	break;
        }
        
        Long accountNo = Long.parseLong(newUserNo) + 1;
        int length = accountNo.toString().length();
        if(length < MIN_USER_NO_NUM){
        	for(int i = length ; i < MIN_USER_NO_NUM ; i ++){
        		account.append("0");//补零
        	}
        }
        account.append(accountNo);
		return account.toString();
	}

	@Override
	public List<String> selectRoleByUserId(String userId){
		return userDao.selectByUserId(userId);
	}

	@Override
	public User selectByPhone(String phone) {
		return userDao.selectByPhone(phone);
	}

	@Override
	public List<String> getMenuListByUserId(String userId) {
		return userDao.getMenuListByUserId(userId);
	}
	
	@Override
	public String selectLoginNameByPhone(String phone) {
		return userDao.selectLoginNameByPhone(phone);
	}

    @Override
    public void registerInfo(RegisterInfo info) {
        User user = new User();
        user.setId(UniqueNumberUtils.get18UniqueNumber());
        user.setUsername(info.getRealName());
        user.setNickname(info.getNickName());
        // 自动生成帐户编号
		String account = getNewUserNo(Constants.OWNER_TYPE);
		user.setLoginname(account);
        user.setPwd(info.getPassword());
        user.setCreatedatetime(new Date());
        user.setState(Constants.INT_ONE);
        user.setPhone(info.getPhone());
        user.setUserType(Constants.OWNER_TYPE);
        user.setIntegral(Constants.ZERO_INTEGRAL);
        //初始登录次数为零
        user.setLoginTimes(Constants.NEW_REGISTERER);
        
        userDao.insert(user);
        
       
        /*CellHouse cellHouse = new CellHouse();
        cellHouse.setId(UniqueNumberUtils.get18UniqueNumber());
        cellHouse.setCellId(info.getCellInfoId());
        cellHouse.setRegionId(info.getCellRegionId());
        cellHouse.setBuildingId(info.getCellBuildingId());
        cellHouse.setUnitId(info.getCellUnitId());
        cellHouse.setName(info.getHouseName());
        
        cellHouseDao.insert(cellHouse);*/
        
        OwnerHouse ownerHouse = new OwnerHouse();
        ownerHouse.setId(UniqueNumberUtils.get18UniqueNumber());
        ownerHouse.setCellId(info.getCellInfoId());
        ownerHouse.setHouseId(info.getHouseId());
        ownerHouse.setOwnerId(user.getId());
        ownerHouse.setState(Constants.SHOP_STATE_NEW);
        
        ownerHouseDao.insert(ownerHouse);
    }
    
    @Override
    public List<String> selectShopUserAccountByOrderId(String id) {
        return userDao.selectShopUserAccountByOrderId(id);
    }
    
    @Override
	public User selectUserByPhoneAndUserType(String phone,int userType) {
    	Map<String, Object> map = new HashMap<String, Object>();
		map.put("phone", phone);
		map.put("userType", userType);
		return  userDao.selectUserByPhoneAndUserType(map);
	}

	@Override
	public Integer selectCountByCompanyId(String[] companyIds, int userType) {
		return userDao.selectCountByCompanyId(companyIds, userType);
	}

	@Override
	public Integer updateLoginTimeAndTimes(User user) {
		User oldUser = userDao.selectByPrimaryKey(user.getId());
		
		if(oldUser.getLoginTimes() == null) {
			oldUser.setLoginTimes(Constants.ZERO_LOGINTIMES);
		}
		oldUser.setLoginTimes(oldUser.getLoginTimes()+1);
		oldUser.setLastLoginTime(new Date());
		
		return userDao.updateLoginTimeAndTimes(oldUser);
	}

}
